package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    /**
     * 课程分页查询
     * @param params
     * @param queryCourseParamsDto
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams params, QueryCourseParamsDto queryCourseParamsDto) {

        //查询
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());
        queryWrapper.eq(CourseBase::getCompanyId, companyId);

        //创建分页参数对象
        Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize());
        //分页查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        PageResult<CourseBase> result = new PageResult<CourseBase>(pageResult.getRecords(), pageResult.getTotal(), params.getPageNo(), params.getPageSize());

        return result;
    }

    /**
     * 新增课程基本信息
     * @param addCourseDto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        //参数的合法性校验
//        if (StringUtils.isBlank(addCourseDto.getName())) {
////            throw new RuntimeException("课程名称为空");
//            XueChengPlusException.cast("课程名称为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getMt())) {
////            throw new RuntimeException("课程分类为空");
//            XueChengPlusException.cast("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getSt())) {
////            throw new RuntimeException("课程分类为空");
//            XueChengPlusException.cast("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getGrade())) {
////            throw new RuntimeException("课程等级为空");
//            XueChengPlusException.cast("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
////            throw new RuntimeException("教育模式为空");
//            XueChengPlusException.cast("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getUsers())) {
////            throw new RuntimeException("适应人群为空");
//            XueChengPlusException.cast("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(addCourseDto.getCharge())) {
////            throw new RuntimeException("收费规则为空");
//            XueChengPlusException.cast("收费规则为空");
//        }

        //向course_base表插入数据
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setStatus("203001");
        courseBase.setAuditStatus("202002");
        int insert = courseBaseMapper.insert(courseBase);
        if(insert < 0){
//            throw new RuntimeException("添加课程失败");
            XueChengPlusException.cast("添加课程失败");
        }

        //向courses_market写入数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseMarket);

        //两张表是一对一，要保证主键一致
        Long id = courseBase.getId();
        courseMarket.setId(id);

        //收费规则
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
//            throw new RuntimeException("收费规则没有选择");
            XueChengPlusException.cast("收费规则没有选择");
        }
        //收费规则为收费
        if(charge.equals("201001")){
            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue()<=0){
//                throw new RuntimeException("课程为收费价格不能为空且必须大于0");
                XueChengPlusException.cast("课程为收费价格不能为空且必须大于0");
            }
        }

        //查找数据是否已经存在这条信息
        CourseMarket market = courseMarketMapper.selectById(id);
        if(market != null){
            courseMarketMapper.deleteById(id);
        }
        courseMarketMapper.insert(courseMarket);


        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        CourseBase courseBase1 = courseBaseMapper.selectById(id);
        if(courseBase1 == null){
            return null;
        }
        CourseMarket courseMarket1 = courseMarketMapper.selectById(id);
        BeanUtils.copyProperties(courseBase1, courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket1, courseBaseInfoDto);

        CourseCategory courseCategory = courseCategoryMapper.selectById(courseBaseInfoDto.getMt());
        courseBaseInfoDto.setMtName(courseCategory.getName());

        CourseCategory courseCategory1 = courseCategoryMapper.selectById(courseBaseInfoDto.getSt());
        courseBaseInfoDto.setStName(courseCategory1.getName());
        return courseBaseInfoDto;
    }

    /**
     * 根据课程ID查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseById(Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);

        //设置大分类名称
        CourseCategory mtObj = courseCategoryMapper.selectById(courseBase.getMt());
        String mtName = mtObj.getName();
        courseBaseInfoDto.setMtName(mtName);

        //设置小分类名称
        CourseCategory stObj = courseCategoryMapper.selectById(courseBase.getMt());
        String stName = stObj.getName();
        courseBaseInfoDto.setStName(stName);
        return courseBaseInfoDto;
    }

    /**
     * 修改课程基本信息
     * @param editCourseDto
     * @return
     */
    @Override
    public CourseBaseInfoDto updateCourseBaseById(Long companyId, EditCourseDto editCourseDto) {

        //数据合法性校验
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null){
            XueChengPlusException.cast("课程不存在");
        }
        if (!courseBase.getCompanyId().equals(companyId)) {
            XueChengPlusException.cast("本机构只能修改本机构的课程信息");
        }

        //封装数据
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());

        int i = courseBaseMapper.updateById(courseBase);
        if(i <= 0){
            XueChengPlusException.cast("修改课程失败");
        }

        //更新营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        courseMarketMapper.updateById(courseMarket);

        return getCourseBaseById(courseId);
    }

    /**
     * 删除课程信息
     * @param courseId
     */
    @Override
    public void deleteCourseBase(Long companyId, Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("本机构只能删除本机构课程");
        }
        LambdaQueryWrapper<CourseMarket> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseMarket::getId, courseId);
        CourseMarket courseMarket = courseMarketMapper.selectOne(queryWrapper1);
        if(courseMarket != null){
            courseMarketMapper.deleteById(courseMarket);
        }else{
            XueChengPlusException.cast("courseMarket为空，删除失败");
        }

//        LambdaQueryWrapper<CourseCategory> queryWrapper2 = new LambdaQueryWrapper<>();
//        queryWrapper2.eq(CourseCategory::getId, courseId);
//        CourseCategory courseCategory = courseCategoryMapper.selectOne(queryWrapper2);
//        if(courseCategory != null){
//            courseCategoryMapper.deleteById(courseCategory);
//        }else{
//            XueChengPlusException.cast("courseCategory为空，删除失败");
//        }

        LambdaQueryWrapper<CourseTeacher> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(CourseTeacher::getCourseId, courseId);
        CourseTeacher courseTeacher = courseTeacherMapper.selectOne(queryWrapper3);
        if(courseTeacher != null){
            courseTeacherMapper.deleteById(courseTeacher);
        }else{
            XueChengPlusException.cast("courseTeacher为空，删除失败");
        }

        LambdaQueryWrapper<Teachplan> queryWrapper4 = new LambdaQueryWrapper<>();
        queryWrapper4.eq(Teachplan::getCourseId, courseId);
        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper4);
        if(teachplans != null){
            for (Teachplan t: teachplans ) {
                //删除课程计划
                teachplanMapper.deleteById(t);
            }
        }else{
            XueChengPlusException.cast("teachplans为空，删除失败");
        }

        LambdaQueryWrapper<TeachplanMedia> queryWrapper5 = new LambdaQueryWrapper<>();
        queryWrapper5.eq(TeachplanMedia::getCourseId, courseId);
        TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(queryWrapper5);
        if(teachplanMedia != null){
            teachplanMediaMapper.deleteById(teachplanMedia);
        }else{
            XueChengPlusException.cast("teachplanMedia为空，删除失败");
        }

        courseBaseMapper.deleteById(courseBase);
    }
}
